﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Services;
using LSBLL;

namespace LSService
{
    /// <summary>
    /// UpFile 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class UpFile : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return String.Empty;
        }

        [WebMethod]
        public bool UpFiles(string fileName, byte[] fs)
        {
            try
            {
                if (String.IsNullOrEmpty(fileName) || fs == null) return false;
                using (var m = new MemoryStream(fs))
                {
                    using (var f = new FileStream(Path.Combine(WebConfig.SavePath, fileName), FileMode.Create))
                    {
                        m.WriteTo(f);
                    }
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// ftp方式上传 
        /// </summary>
        [WebMethod]
        public int UploadFtp(string filePath, string filename, string ftpServerIp, string ftpUserId, string ftpPassword)
        {
            var fileInf = new FileInfo(filePath + "\\" + filename);
            var uri = "ftp://" + ftpServerIp + "/" + fileInf.Name;
            // Create FtpWebRequest object from the Uri provided 
            var reqFTP = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpServerIp + "/" + fileInf.Name));
            try
            {
                // Provide the WebPermission Credintials 
                reqFTP.Credentials = new NetworkCredential(ftpUserId, ftpPassword);

                // By default KeepAlive is true, where the control connection is not closed 
                // after a command is executed. 
                reqFTP.KeepAlive = false;

                // Specify the command to be executed. 
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

                // Specify the data transfer type. 
                reqFTP.UseBinary = true;

                // Notify the server about the size of the uploaded file 
                reqFTP.ContentLength = fileInf.Length;

                // The buffer size is set to 2kb 
                const int buffLength = 2048;
                var buff = new byte[buffLength];

                // Opens a file stream (System.IO.FileStream) to read the file to be uploaded 
                //FileStream fs = fileInf.OpenRead(); 
                using (var fs = fileInf.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    // Stream to which the file to be upload is written 
                    using (var strm = reqFTP.GetRequestStream())
                    {
                        // Read from the file stream 2kb at a time 
                        var contentLen = fs.Read(buff, 0, buffLength);

                        // Till Stream content ends 
                        while (contentLen != 0)
                        {
                            // Write Content from the file stream to the FTP Upload Stream 
                            strm.Write(buff, 0, contentLen);
                            contentLen = fs.Read(buff, 0, buffLength);
                        }
                        return 0;
                    }
                }
            }
            catch (Exception ex)
            {
                reqFTP.Abort();
                //  Logging.WriteError(ex.Message + ex.StackTrace);
                return -2;
            }
        }

        /// <summary>
        /// ftp方式下载 
        /// </summary>
        [WebMethod]
        public int DownloadFtp(string filePath, string fileName, string ftpServerIp, string ftpUserId, string ftpPassword)
        {
            try
            {
                //filePath = < <The full path where the file is to be created.>>, 
                //fileName = < <Name of the file to be created(Need not be the name of the file on FTP server).>> 
                using (var outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create))
                {
                    var reqFTP = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpServerIp + "/" + fileName));
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                    reqFTP.UseBinary = true;
                    reqFTP.KeepAlive = false;
                    reqFTP.Credentials = new NetworkCredential(ftpUserId, ftpPassword);

                    using (var response = (FtpWebResponse)reqFTP.GetResponse())
                    {
                        using (var ftpStream = response.GetResponseStream())
                        {
                            if (ftpStream != null)
                            {
                                var cl = response.ContentLength;
                                const int bufferSize = 2048;
                                var buffer = new byte[bufferSize];
                                var readCount = ftpStream.Read(buffer, 0, bufferSize);
                                while (readCount > 0)
                                {
                                    outputStream.Write(buffer, 0, readCount);
                                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                                }
                                return 0;
                            }
                            return -1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Logging.WriteError(ex.Message + ex.StackTrace);
                // System.Windows.Forms.MessageBox.Show(ex.Message);
                return -2;
            }
        }
    }
}
